package com.uni.utils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory factory;

    /** 单例模式创建工厂 只执行一次**/
    static {
        try{
            String resource = "mybatis-config.xml";
            // 1. 获取 mybatsi-config.xml 的输入流
            InputStream is = Resources.getResourceAsStream(resource);
            // 2. 创建 SqlSessionFactory对象，完成对配置文件的读取
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession(){
        return factory.openSession();
    }
}
